var api = {

    initlSelectPara: "",
    initdeviceNameSelectPara: "",
    initdeviceItSelectPara: "",
    selectCell: null,
    clone: null,
    sysEnergyType: sessionStorage.getItem('sysEnergyType'),
    changeTmpl: function (e, objectId, fieldCode) {

        var temp2 = "#" + this.initdeviceNameSelectPara;
        var getDevices = BaseURL + "pubinfo/modelconfig/getDevices";// 其他设备名称url
        var getBusbars = BaseURL + "pubinfo/modelconfig/getBusbars";// 母线名称url
        var getPhyunits = BaseURL + "pubinfo/modelconfig/getPhyunits";// 设备名称url

        if (null != this.selectCell) {
            //this.selectCell.value.setAttribute("CimType",""+e.value);
            this.clone.setAttribute("CimType", "" + e.value);//模板:CimType,设备ID:RefId,属性:RefCode
            this.selectCell.value = this.clone;
        }

        let idMpa = {
            301: 'phyunitId',
            302: 'busId',
            'def': 'deviceId'
        }

        let objectUrl = {
            301: getPhyunits,
            302: getBusbars,
            'def': getDevices
        }

        var objParams = {
            pageSize: 99999,
            pageNum: 1,
            phyunitName: '',
            busName: ''
        };

        let htMap = {
            301: { val: 'phyunitName', label: 'phyunitName' },
            302: { val: 'busName', label: 'busName' },
            'def': { val: 'deviceName', label: 'deviceName' }
        }
        let htAct = htMap?.[e.value] || htMap.def

        let idAct = idMpa?.[e.value] || idMpa.def

        objParams.deviceType = e.value;

        $(temp2).empty();
        let val = e.value
        // 风电用户-设备类型选择风电（308）查询机组（301）的设备列表
        if (e.value == 308 && api.sysEnergyType == 'WIND') {
            val = 301
            objParams.deviceType = 301;
            htAct = htMap[301]
            idAct = idMpa[301]
        }
        this.getDeviceList(objectUrl?.[val] || objectUrl.def, objParams, function (acceptDevLi) {
            let selected = ''
            $(temp2).append("<option value>请选择</option>");
            for (var i = 0; i < acceptDevLi.rows.length; i++) {
                if (e.value !== 301 && e.value !== 302) {
                    $(temp2).append("<option id='" + acceptDevLi.rows[i][idAct] + "' value='" + acceptDevLi.rows[i][htAct.val] + "'>" + acceptDevLi.rows[i][htAct.label] + "</option>");
                } else {
                    if (i > 0) {
                        $(temp2).append("<option value='" + acceptDevLi.rows[i][htAct.val] + "'>" + acceptDevLi.rows[i][htAct.label] + "</option>");
                    }
                }
                if (fieldCode != null) {
                    if (fieldCode == acceptDevLi.rows[i][idAct]) {
                        selected = acceptDevLi.rows[i][htAct.val]
                    }
                    $("#deviceNameSelect  option[value='" + selected + "']").attr("selected", "selected");
                }
            }
            api.changeRef({ ...e, value: selected }, objectId)
        });

    },

    changeRef: function (e, objectId) {
        var temp = "#" + this.initlSelectPara;
        var temp3 = "#" + this.initdeviceItSelectPara;
        var itemParams = {
            channel: '',
            associationType: '',
            mesaType: 201,
            devName: '',
            devType: $(temp).val(),
            meterName: '',
            pageSize: 9999,
            pageNum: 1,
            channelGroupId: this.thfareCode,
            dictEnName: ''
        };

        if (api.sysEnergyType == 'WIND') {
            // itemParams.meterName = e.value;
            itemParams.devName = e.value;
        } else {
            itemParams.devName = e.value;
        }

        var objectItemUrl = BaseURL + "pubinfo/modelconfig/getMeters"; // 量测列表

        if (null != this.selectCell) {
            $(e.childNodes).each((index, value) => {
                if (e.value == $(value)[0].value) {
                    this.clone.setAttribute("RefCode", "" + $(value).attr('id'));
                }
            })
            // this.clone.setAttribute("RefCode", "" + e.value);
            this.selectCell.value = this.clone;
        }

        $(temp3).empty();

        Promise.all([
            this.getDeviceItem(objectItemUrl, { ...itemParams, mesaType: 201 }),
            this.getDeviceItem(objectItemUrl, { ...itemParams, mesaType: 202 }),
            this.getDeviceItem(objectItemUrl, { ...itemParams, mesaType: 203 }),
            this.getDeviceItem(objectItemUrl, { ...itemParams, mesaType: 204 }),
        ]).then((values) => {
            let acceptDevIt = [...values[0].rows, ...values[1].rows, ...values[2].rows, ...values[3].rows]
            $(temp3).append("<option value>请选择</option>");
            // $(temp3).append("<option value='#'>设备ID</option>");
            for (var i = 0; i < acceptDevIt.length; i++) {
                $(temp3).append("<option mesaType='" + acceptDevIt[i].mesaType + "' value='" + acceptDevIt[i].meterId + "'>" + acceptDevIt[i].meterName + "</option>");
            }
            if (objectId != null) {
                $("#deviceItSelect  option[value='" + objectId + "']").attr("selected", "selected");
            }
        })

        // this.getDeviceItem(objectItemUrl, itemParams, function (acceptDevIt) {});
    },

    changeRefItem: function (e) {

        if (null != this.selectCell) {
            // $(e.childNodes).each((index, value)=> {
            //     if(e.value == $(value)[0].value) {
            //         this.clone.setAttribute("RefCode", "" + $(value).attr('mesaType'));
            //     }
            // })
            // this.selectCell.value.setAttribute("CimType",""+e.value);
            this.clone.setAttribute("RefId", "" + e.value);
            this.selectCell.value = this.clone;
        }

    },

    changeDraw: function (e) {
        if (null != this.selectCell) {
            //this.selectCell.value.setAttribute("CimType",""+e.value);
            this.clone.setAttribute("drawName", "" + e.value);
            this.selectCell.value = this.clone;
        }
    },

    //清除按钮
    clearContent: function () {
        $('#tmplSelect option:selected').attr("selected", false);
        // $('.geFormatContainer div:visible option:selected').attr("selected", false);

        $('.geFormatContainer div:visible select:eq(1)').empty();
        $('.geFormatContainer div:visible select:eq(2)').empty();
        $('.geFormatContainer div:visible select:eq(3)').empty();

        $('.geFormatContainer div:visible select:eq(1)').append("<option value>请选择</option>");
        $('.geFormatContainer div:visible select:eq(2)').append("<option value>请选择</option>");
        $('.geFormatContainer div:visible select:eq(3)').append("<option value>请选择</option>");


    },

    // 通道change
    changeThfare: function (e, objectId, fieldCode, thfareCode) {
        this.thfareCode = e.value
        this.clone.setAttribute("Thfare", "" + e.value);
        this.clone.setAttribute("RefId", "");
        this.selectCell.value = this.clone;
        var temp = "#" + this.initlSelectPara;
        var temp2 = "#" + this.initdeviceNameSelectPara;
        var temp3 = "#" + this.initdeviceItSelectPara;
        var objectItemUrl = BaseURL + "pubinfo/modelconfig/getMeters"; // 量测列表
        var itemParams = {
            channel: '',
            associationType: '',
            mesaType: 201,
            devName: $(temp2).val(),
            devType: $(temp).val(),
            meterName: '',
            pageSize: 9999,
            pageNum: 1,
            channelGroupId: e.value,
            dictEnName: ''
        };
        $(temp3).empty();
        Promise.all([
            this.getDeviceItem(objectItemUrl, { ...itemParams, mesaType: 201 }),
            this.getDeviceItem(objectItemUrl, { ...itemParams, mesaType: 202 }),
        ]).then((values) => {
            let acceptDevIt = [...values[0].rows, ...values[1].rows]
            $(temp3).append("<option value>请选择</option>");
            for (var i = 0; i < acceptDevIt.length; i++) {
                $(temp3).append("<option mesaType='" + acceptDevIt[i].mesaType + "' value='" + acceptDevIt[i].meterId + "'>" + acceptDevIt[i].meterName + "</option>");
            }
            if (objectId != null) {
                $("#deviceItSelect  option[value='" + objectId + "']").attr("selected", "selected");
            }
        })
    },

    //初始化下拉框
    init: function (tmplSelectPara, deviceNameSelectPara, deviceItSelectPara, sc, clone, thfareSelect) {
        this.initlSelectPara = tmplSelectPara;
        this.initdeviceNameSelectPara = deviceNameSelectPara;
        this.initdeviceItSelectPara = deviceItSelectPara;
        this.selectCell = sc;
        this.clone = clone;
        this.clone = clone;
        var temp = "#" + tmplSelectPara;
        var cimtype = typeof (sc.value) == "object" ? sc.value.getAttribute("CimType") : null;
        var objectId = typeof (sc.value) == "object" ? sc.value.getAttribute("RefId") : null;
        var fieldCode = typeof (sc.value) == "object" ? sc.value.getAttribute("RefCode") : null;
        var thfareCode = typeof (sc.value) == "object" ? sc.value.getAttribute("Thfare") : null; // 通道id
        this.thfareCode = thfareCode
        api.getThfareList(function (acceptTmp) {
            for (var i = 0; i < acceptTmp.rows.length; i++) {
                id = acceptTmp.rows[i].id;
                $('#' + thfareSelect).append("<option value='" + acceptTmp.rows[i].id + "'>" + acceptTmp.rows[i].groupName + "</option>");
            }

            if (sc.value != null) {
                if (thfareCode != null) {
                    $("#" + thfareSelect + "  option[value='" + thfareCode + "']").attr("selected", "selected");
                }
            }
        })

        api.getTmplList(function (acceptTmp) {

            for (var i = 0; i < acceptTmp.data.length; i++) {
                id = acceptTmp.data[i].id;
                $(temp).append("<option value='" + acceptTmp.data[i].dictActualValue + "'>" + acceptTmp.data[i].dictName + "</option>");
            }

            if (sc.value != null) {
                if (cimtype != null) {
                    $("#" + tmplSelectPara + "  option[value='" + cimtype + "']").attr("selected", "selected");

                    var cimTypeObj = {};
                    cimTypeObj["value"] = cimtype;
                    api.changeTmpl(cimTypeObj, objectId, fieldCode);

                }
            }
        });

        // if(cimtype != null){
        //     api.getAtrbPromise(cimtype, function(acceptAtrbPromise){
        //         let staticFormItem = '';		// 静态属性dom
        //         // 动态创建表单
        //         let inputFormItemDom = ''; // 页面输入框dom

        //         for(var i = 0; i < acceptAtrbPromise.result.length; i++){
        //             if(acceptAtrbPromise.result[i].atrbType == IOT_ATRB_TYPE.STATIC){

        //             }
        //         }
        //     });
        // }

    },
    getTmplList: function (resFlag) {

        $.ajax({
            type: 'GET',
            url: BaseURL + "pubinfo/modelconfig/getRelatedDeviceTypes",
            success: (res) => {
                resFlag(res)
            },
            beforeSend: function (request) {
                request.setRequestHeader("isSwagger", "true");
                request.setRequestHeader('Authorization', 'Bearer ' + JSON.parse(JSON.parse(window.sessionStorage.getItem('layuiAdmin')).Authorization).value);
            },
            error: (error) => {
                console.log("error");
            }
        })
    },

    getDeviceList: function (objectUrl, objParams, resFlag) {
        $.ajax({
            type: 'Get',
            // url: BaseURL+"/iot-admin/iot/object/",
            // data: data,
            url: objectUrl,
            data: objParams,
            success: (res) => {
                resFlag(res)
            },
            beforeSend: function (request) {
                request.setRequestHeader("isSwagger", "true");
                request.setRequestHeader('Authorization', 'Bearer ' + JSON.parse(JSON.parse(window.sessionStorage.getItem('layuiAdmin')).Authorization).value);
            },
            error: (error) => {

                console.log("error");
            }
        })
    },

    getDeviceItem: function (objectItemUrl, itemParams, resFlag) {

        return $.ajax({
            type: 'GET',
            url: objectItemUrl,
            data: itemParams,
            success: (res) => {
                if (resFlag) {
                    resFlag(res)
                }
            },
            beforeSend: function (request) {
                request.setRequestHeader("isSwagger", "true");
                request.setRequestHeader('Authorization', 'Bearer ' + JSON.parse(JSON.parse(window.sessionStorage.getItem('layuiAdmin')).Authorization).value);
            },
            error: (error) => {

                console.log("error");
            }
        })
    },

    getAtrbPromise: function (cimtype, resFlag) {
        $.ajax({
            type: 'GET',
            url: BaseURL + "iot-admin/iot/template/atrb/" + cimtype,
            // data: {size='-1',
            success: (res) => {
                resFlag(res)
            },
            beforeSend: function (request) {
                request.setRequestHeader("isSwagger", "true");
                request.setRequestHeader('Authorization', 'Bearer ' + JSON.parse(JSON.parse(window.sessionStorage.getItem('layuiAdmin')).Authorization).value);
            },
            error: (error) => {

                console.log("error");
            }
        })
    },

    getDrawList: function (resFlag) {

        $.ajax({
            type: 'GET',
            url: BaseURL + "draw/drawWiringDiagramInfo/?size=-1",
            // data: {size='-1',
            success: (res) => {
                resFlag(res)
            },
            beforeSend: function (request) {
                request.setRequestHeader("isSwagger", "true");
                request.setRequestHeader('Authorization', 'Bearer ' + JSON.parse(JSON.parse(window.sessionStorage.getItem('layuiAdmin')).Authorization).value);
            },
            error: (error) => {

                console.log("error");
            }
        })
    },

    getThfareList: function (resFlag) {

        $.ajax({
            type: 'GET',
            url: BaseURL + "pubinfo/modelconfig/getChannelGroups",
            data: {
                pageSize: 9999,
                total: 0,
                pageNum: 1
            },
            success: (res) => {
                resFlag(res)
            },
            beforeSend: function (request) {
                request.setRequestHeader("isSwagger", "true");
                request.setRequestHeader('Authorization', 'Bearer ' + JSON.parse(JSON.parse(window.sessionStorage.getItem('layuiAdmin')).Authorization).value);
            },
            error: (error) => {
                console.log("error");
            }
        })
    },
}